package edu.gyc.swing;


import javax.imageio.ImageIO;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

class PhotoFrame extends JFrame   {
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    private JFileChooser fileChooser = new JFileChooser();
    private List<String> picFilePaths = new ArrayList<>();
    private String currentPicPath;
    private JButton previousBt,nextBt;
    private JLabel picLabel,statusLabel;
    private boolean indexPathOk=false;
    private int count=0;
    private Timer timer ;
    public PhotoFrame()  {
        super("PhotoViewer");
        setSize(WIDTH,HEIGHT);
        JMenuBar menuBar = new JMenuBar();
        //setJMenuBar(menuBar);
       // JMenu menu = new JMenu("File");
        JMenuItem openItem = new JMenuItem("打开文件夹");
     //   menu.add(openItem);
        menuBar.add(openItem);
        JMenuItem carouselItem = new JMenuItem("幻灯播放");
        menuBar.add(carouselItem);

        JPanel panel = new JPanel();
        JButton openBt = new JButton("Open");
        JButton carouselBt = new JButton("幻灯播放");
        panel.add(openBt);
        panel.add(carouselBt);
        getContentPane().add(panel, BorderLayout.NORTH);
        fileChooser.setCurrentDirectory(new File("."));
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("ImageFiles", "jpg"
                , "jpeg");
        fileChooser.setFileFilter(fileNameExtensionFilter);
        openBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser.setCurrentDirectory(new File("."));
                int result = fileChooser.showOpenDialog(null);
                indexPathOk=false;
                enableBt();
                if (result == JFileChooser.APPROVE_OPTION) {
                    currentPicPath=fileChooser.getSelectedFile().getAbsolutePath();
                    String picDir=fileChooser.getSelectedFile().getParent();
                   scalePic(currentPicPath);
                   asyncGetPicPath(picDir);
                }
                picLabel.requestFocus();
            }
        });

        carouselBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                picLabel.requestFocus();
                timer = new Timer();
                TimerTask timerTask=new TimerTask() {
                    @Override
                    public void run() {
                        count++;
                        if (count >= picFilePaths.size()) {
                            count=0;
                        }
                        scalePic(picFilePaths.get(count));
                    }
                };

                timer.schedule(timerTask,0,3000);

            }
        });
/*
        nextBt = new JButton("下一幅");
        nextBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (timer != null) {
                    timer.cancel();
                }
               count++;
                if (count >= picFilePaths.size()) {
                    count=0;
                }
                scalePic(picFilePaths.get(count));
            }
        });
        previousBt = new JButton("上一副");
        previousBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (timer != null) {
                    timer.cancel();
                }
                count--;
                if (count<0) {
                    count=picFilePaths.size()-1;
                }
                scalePic(picFilePaths.get(count));
            }
        });

        if (!indexPathOk) {
            previousBt.setEnabled(false);
            nextBt.setEnabled(false);
        }
        getContentPane().add(previousBt, BorderLayout.WEST);
        getContentPane().add(nextBt, BorderLayout.EAST);
    */
        picLabel = new JLabel();
        picLabel.addKeyListener(new MyKeyListener());

        getContentPane().add(picLabel, BorderLayout.CENTER);


        statusLabel = new JLabel("当前文件是：");
        getContentPane().add(statusLabel, BorderLayout.SOUTH);


    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
        setVisible(true);

      asyncGetPicPath();


      picLabel.requestFocus();


    }

    private void scalePic(String path) {
        ImageIcon icon=new ImageIcon(path);
        //等比缩放条件
        int imgWidth=icon.getIconWidth();
        int imgHeight=icon.getIconHeight();
        System.out.println("imgWidth: "+imgWidth+" imgHeight:"+imgHeight);
        int targetWidth= picLabel.getWidth();
        int targetHeight= picLabel.getHeight();
        System.out.println("targetWidth: "+targetWidth+" targetHeight:"+targetHeight);


        int reImgWidth= 0;
        int reImgHeight= 0;
        if (imgHeight > targetHeight) {
            float resize= (float) (targetHeight*1.0/imgHeight);
            System.out.println("resize: "+resize);

            reImgWidth= (int) (imgWidth*resize);
             reImgHeight= (int) (imgHeight*resize);
        }else {
            reImgWidth=imgWidth;
            reImgHeight=imgHeight;
        }

        //这个是按等比缩放
        icon=new ImageIcon(icon.getImage().getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_DEFAULT));
        picLabel.setIcon(icon);
        picLabel.setHorizontalAlignment(SwingConstants.CENTER);

        statusLabel.setText("当前文件："+path+" widht:"+imgWidth+" height:"+imgHeight);
    }

    private void showPic() {

    }
    public void getDirPicPath(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            JOptionPane.showMessageDialog(null,dir+" 路径不存在！");
        }
        File[] files=file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith("jpg") || name.endsWith("jpeg") ) {
                    return true;
                }
                return false;
            }
        });
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            try {
                if (ImageIO.read(f) != null) {
                    picFilePaths.add(f.getAbsolutePath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(picFilePaths);

    }

    public void asyncGetPicPath() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String desktopPath = FileSystemView.getFileSystemView().getDefaultDirectory().getParent();

                getDirPicPath(desktopPath+"/Pictures");
                JOptionPane.showMessageDialog(null,"系统图片目录文件检索完毕，共有图片"+picFilePaths.size());
                if (picFilePaths.size() > 0) {
                    indexPathOk=true;
                    String path = picFilePaths.get(0);
                    scalePic(path);
                }

                enableBt();
            }
        }).start();
    }

    public void asyncGetPicPath(String path) {
        picFilePaths.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {


                getDirPicPath(path);
                JOptionPane.showMessageDialog(null,path+"目录文件检索完毕，共有图片"+picFilePaths.size());
                if (picFilePaths.size() > 0) {
                    indexPathOk=true;
                    String path = picFilePaths.get(0);
                    scalePic(path);
                }
                enableBt();

            }
        }).start();
    }

    private void enableBt() {
        previousBt.setEnabled(indexPathOk);
        nextBt.setEnabled(indexPathOk);
    }

   class MyKeyListener implements KeyListener{
       @Override
       public void keyTyped(KeyEvent e) {

       }

       @Override
       public void keyPressed(KeyEvent e) {
           System.out.println("key pressed "+e);
           switch (e.getKeyCode()) {
               case KeyEvent.VK_LEFT:
                   System.out.println("key left");
                   if (timer != null) {
                       timer.cancel();
                   }
                   count--;
                   if (count<0) {
                       count=picFilePaths.size()-1;
                   }
                   scalePic(picFilePaths.get(count));
                   break;
               case KeyEvent.VK_RIGHT:
                   System.out.println("key right");
                   if (timer != null) {
                       timer.cancel();
                   }
                   count++;
                   if (count >= picFilePaths.size()) {
                       count=0;
                   }
                   scalePic(picFilePaths.get(count));
                   break;

           }
       }

       @Override
       public void keyReleased(KeyEvent e) {

       }
   }
}
public class MyPhoto {
    public static void main(String[] args) {
        PhotoFrame frame=new PhotoFrame();

    }
}
